package com.loong.web.gp4j.service.user;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.loong.web.gp4j.bean.param.user.UserDetailParam;
import com.loong.web.gp4j.bean.schema.user.UserDetailSchema;
import com.loong.web.gp4j.dao.user.UserDetailDao;
import com.loong.web.suppert.auth.User;
import com.loong.web.suppert.auth.UserSessions;
import com.loong.web.suppert.collection.valid.ErrorList;

/**
 * 用户详情服务
 *
 * @author 张成轩
 */
@Service
public class UserDetailService {

	@Resource
	private UserDetailDao userDetailDao;

	/**
	 * 获取用户详情信息
	 * 
	 * @param request 请求
	 * @param param 参数
	 */
	public void setUserDetail(HttpServletRequest request, UserDetailParam param) {

		User user = UserSessions.getUser(request);
		UserDetailSchema schema = userDetailDao.getByUserId(user.getId());
		UserDetailAdapter.convert(schema, param);
	}

	/**
	 * 保存用户详情
	 * 
	 * @param request 请求
	 * @param param 参数
	 * @param errorList 错误集合
	 * @return 返回对象
	 */
	public boolean saveUserDetail(HttpServletRequest request, UserDetailParam param, ErrorList errorList) {

		User user = UserSessions.getUser(request);
		UserDetailSchema schema = userDetailDao.getByUserId(user.getId());
		int count = 0;
		if (schema == null) {
			// 插入
			schema = new UserDetailSchema();
			schema.setUserId(user.getId());
			UserDetailAdapter.convert(param, schema);
			count = userDetailDao.insert(schema);
		} else {
			// 更新
			UserDetailAdapter.convert(param, schema);
			count = userDetailDao.update(schema);
		}
		if (count != 1) {
			errorList.addError("更新失败");
			return false;
		}
		return true;
	}
}
